<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="班组编号">
          <el-input
            v-model="searchParam.teamCode"
            placeholder="请输入班组编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="班组名称">
          <el-input
            v-model="searchParam.teamName"
            placeholder="请输入班组名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="班组类型">
          <el-select
            v-model="searchParam.teamType"
            placeholder="请选择班组类型"
            clearable
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('mouldTeamType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="stopParam()"
          ><i-ep-delete />批量停用</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="班组编号"
          prop="teamCode"
          min-width="100"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="班组名称"
          prop="teamName"
          min-width="100"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="班组类型"
          prop="teamType"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("mouldTeamType", scope.row.teamType) }}
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="是否启用"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogMember(scope.row)"
              ><i-ep-user />成员</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >

            <!-- <el-dropdown size="small">
              <el-button type="primary" size="small" style="width: 75px">
                更多菜单
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openDialogdetail(scope.row)"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item @click="openDialog(scope.row)"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item @click="openDialogMember(scope.row)"
                    >成员</el-dropdown-item
                  >
                  <el-dropdown-item @click="openDialogDevice(scope.row)"
                    >设备</el-dropdown-item
                  >
                  <el-dropdown-item @click="handleTableDelete(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown> -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eamteam-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <eamteam-member-edit
      :visible="addDialogMember.visible"
      :title="addDialogMember.title"
      :data="addDialogMember.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialogMember.readvisible"
      @change-visible="changeVisibleMember"
    />
    <eamteam-device-edit
      :visible="addDialogDevice.visible"
      :title="addDialogDevice.title"
      :data="addDialogDevice.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialogDevice.readvisible"
      @change-visible="changeVisibleDevice"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EAMTEAM",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/eamTeam/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetKind: 3,
  teamCode: "",
  teamName: "",
  teamType: "",
  plantId: "",
  workCenterId: "",
};

const deleteParam = {
  api: "/eam/eamTeam/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamTeam/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开班组表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改班组";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增班组";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开班组表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "班组详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 打开人员弹窗
const addDialogMember: any = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  crewMembersData: [],
});
/** 打开人员弹窗 详情 */
// 获取人员详情
async function getInfoMember(id: string) {
  request({
    url: `/eam/eamTeam/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialogMember.data = data.data;
      addDialogMember.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
function openDialogMember(roleObj?: Object) {
  if (roleObj) {
    addDialogMember.title = "编辑人员信息";
    getInfoMember(roleObj.id);
  }
  addDialogMember.readvisible = false;
}

function changeVisibleMember(value: boolean) {
  addDialogMember.visible = value;
  if (!value) {
    addDialogMember.data = {};
  }
}

// 打开设备弹窗
const addDialogDevice: any = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
/** 打开设备弹窗 详情 */
async function getInfoDevice(id: string) {
  request({
    url: `/eam/eamTeam/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialogDevice.data = data.data;
      addDialogDevice.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
function openDialogDevice(roleObj?: Object) {
  if (roleObj) {
    addDialogDevice.title = "编辑设备信息";
    getInfoDevice(roleObj.id);
  }
  addDialogDevice.readvisible = false;
}

function changeVisibleDevice(value: boolean) {
  addDialogDevice.visible = value;
  if (!value) {
    addDialogDevice.data = {};
  }
}

// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};
// 根据工厂id 查询中心
const workCenterValue: any = ref([]);
const workCenterList = async (id) => {
  if (id != "") {
    const res2: any = await request({
      url: `/eam/mesworkshop/getList`,
      method: "post",
      data: { enabled: 1, plantId: id },
    });
    workCenterValue.value = res2.data;
  } else {
    workCenterValue.value = [];
  }
};
/** 选择工厂时触发 根据Code赋值Id*/

const changePlant = (id) => {
  workCenterValue.value = [];
  workCenterList(id);
};
onMounted(() => {
  getPlantList();
});
//批量停用
const stopParam = async () => {
  ElMessageBox.confirm("确定批量停用吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/eam/eamTeam/disabled",
        method: "post",
        data: { ids: ids.value },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量停用成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消停用",
      });
    });
};

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/eamTeam/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功！");
      search();
    });
  });
}
</script>
